package com.czk.netty.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/21 11:28
 */
public class MyNettyHandler extends ChannelInboundHandlerAdapter {
    private static Logger LOGGER = LoggerFactory.getLogger(MyNettyHandler.class);
    SocketChannel channel = null;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 拿到channel
        channel = (SocketChannel) ctx.channel();
        LOGGER.info("连接成功");
        LOGGER.info("远程链接地址" + channel.getRemoteAddress());
        // 构建消息
        String message = "连接成功" + LocalDateTime.now();
        ctx.writeAndFlush(message);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        LOGGER.info(new SimpleDateFormat("yyyy-dd-MM hh:mm:ss").format(new Date()) + "  服务单收到消息了 " + msg);
        String message = "服务端收到消息" + msg;
        ctx.writeAndFlush(message);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info(channel.getRemoteAddress() + "断开连接了");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.error("服务端异常" + cause.getMessage());
        ctx.close();
    }
}
